/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package view;

/**
 *
 * @author aeguzkiza
 */

import GUI.JFrameBase;
import javax.swing.text.Position;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreePath;
import libraries.Application;
import libraries.FunctionLibrary;
import model.DB2Hash;
import view.PatientPanelView;

public class PatientTreeView {
    PatientPanelView patientPanelView;
    // Declare global variables.
    private Patient patient;
    private Study study;
    private Acquisition acquisition;

    private DefaultMutableTreeNode patientNode;
    private DefaultMutableTreeNode studyNode;
    private DefaultMutableTreeNode acquisitionNode;
    //private String lastPatient = "";
    private final JFrameBase frame;
    private FunctionLibrary LF = new FunctionLibrary();

    public PatientTreeView(JFrameBase frame) {
        this.frame = frame;
        this.patientPanelView = new PatientPanelView(frame);
        this.patient = new Patient(frame.newPatient, null, null);
        frame.topPatient.add(new DefaultMutableTreeNode(patient)); // Inserts the first patient by default (New patient).
    }

    public void updateViewAddPatient(Integer patientId,String Name,String SurName) {
                
        this.patient = new Patient(Name,SurName, patientId);
        this.patientNode = new DefaultMutableTreeNode(patient);
        LF.addNodeInSortedOrder(frame.topPatient,patientNode);  // Adds a new Patient in the root node alphabetically sorted.
        //frame.topPatient.add(patientNode);

        this.study = new Study(frame.newStudy, null, false);
        this.patientNode.add(new DefaultMutableTreeNode(study));
    }
    
    public void updateViewEditPatient(boolean isNew, String oldName, String oldSurName, Integer patientId, String Name, String SurName) {
        
        String oldPatientsFullName = oldName+" "+oldSurName;
        
        if (Name != null || SurName != null ) {
            if(isNew){  
                updateViewAddPatient(patientId, Name, SurName);  // Add a new Patient node in the JTree.
            }else{  // Search the node in the tree to change it.
                TreePath path = updateViewSearch(oldPatientsFullName);
                System.out.println("Path: "+path);
                if(path != null){
                    DefaultMutableTreeNode changedNode = (DefaultMutableTreeNode)(MutableTreeNode) path.getLastPathComponent();    // Get's a node by it's path.

                    Patient x = (view.Patient)changedNode.getUserObject();
                    x.setPatientName(Name, SurName);
                }
            }
            frame.modelPatient.reload();
            
        }else{
            System.out.println("The search textField is empty");
        }
        
    }
    public String updateViewAddStudy(DefaultMutableTreeNode parentNode, Integer studyId, String StudyDate, String worklistId, int revised) {
        this.acquisitionNode = null;    // Initializes acquisition variable when a new study is created.
        if(revised == 1 || worklistId.isEmpty()){
            // Create study node:
            this.study = new Study(frame.parseDate(StudyDate), studyId, false);
            this.studyNode = new DefaultMutableTreeNode(study);
            // Add empty acquisition node:
            this.acquisition = new Acquisition(frame.newAcquisition,"", null, false);
            acquisitionNode = new DefaultMutableTreeNode(acquisition);
            this.studyNode.add(acquisitionNode);
            // Add study node to its parent:
            if(parentNode == null){
                LF.addNodeInSortedOrder(this.patientNode,studyNode);    // Adds new acquisition study sorted on the last patient.
                //this.patientNode.add(studyNode);   // Adds current study at start of the corresponding patient.
            
            }else{  // NOT USED, even not parentNode.
                LF.addNodeInSortedOrder(parentNode,studyNode);  // Adds new study alfabetically sorted on the selected patient.
                //parentNode.add(studyNode);   // Adds current study at start of the corresponding patient.
            }
        }
        return study.toString();
    }
    public void updateViewEditStudy(boolean isNew, String Name, String SurName, String oldStudydate, Integer studyId, String studyDate){
        System.out.println(">>> START OF updateViewEditStudy");
        //String createdStudyName = null; // Catches the name of the new node.
        if (studyDate != null ) {
            System.out.println("isNew: "+isNew);
            if(isNew){  
                // Select current patient.
                String currentPatientsFullName = Name+" "+SurName;
                TreePath path = updateViewSearch(currentPatientsFullName);
                if(path != null){   // Case of being a Patient, write the study inside its node.
                    DefaultMutableTreeNode changedNode = (DefaultMutableTreeNode)(MutableTreeNode) path.getLastPathComponent(); // Get the node of patient where we want to add a study. .
                    updateViewAddStudy(changedNode, studyId, studyDate, null, 1);  // Add a new Study node in a patient from JTree.
                }              
                
            }else{  // Change the study node read from DB by a modifyed one.
                TreePath path = updateViewSearch(frame.parseDate(oldStudydate));
                System.out.println("oldStudydate: "+frame.parseDate(oldStudydate)+" Path: "+path);
                if(path != null){
                    DefaultMutableTreeNode changedNode = (DefaultMutableTreeNode)(MutableTreeNode) path.getLastPathComponent();    // Get's a node by it's path.

                    Study y = (view.Study)changedNode.getUserObject();
                    y.setDate(studyDate);
                    y.setWorklist(false);
                    //createdStudyName = y.toString();
                }
            }

            frame.modelPatient.reload();
            //updateViewSearch(createdStudyName); // Selects the last created node.
        }else{
            System.out.println("The search textField is empty");
        }
        
    }
    //public void updateViewAddAcquisition(Integer acquisitionId,String AcquisitionTime,String AcquisitionName,String ImageLaterality,Integer StudyId) {
    public void updateViewAddAcquisition(DefaultMutableTreeNode parentNode, Integer acquisitionId, String ImageLaterality, String AcquisitionTime, Integer revised) {
        //System.out.println("studyId: "+this.study.id+" studyNode: "+this.studyNode);
                     
        //if(studyNodeString != null && this.study.id.equals(StudyId)){ // There's no matched node AND if there is, the node ID is the correct one.
        if(revised == 1 && this.studyNode != null){ // There's no matched node AND if there is, the node ID is the correct one.
            //String studyNodeString = studyNode.toString();
            //System.out.println("PATIENT Current Study ID: "+this.study.id+" ? StudyId: "+StudyId+" Current Study DATE: "+this.study.date);
            //if(this.study.id.equals(StudyId)){
                // Translation of the eye nomenclature.
                String eye = LF.eyeTranslation(ImageLaterality);
                
                this.acquisition = new Acquisition(eye,frame.parseTime(AcquisitionTime), acquisitionId, false);
                acquisitionNode = new DefaultMutableTreeNode(acquisition);
                if(parentNode == null){
                    LF.addNodeInSortedOrder(this.studyNode,acquisitionNode);    // Adds new acquisition alfabetically sorted on the last study.
                    //this.studyNode.add(acquisitionNode);   // Adds new acquisition at start of each study.
                }else{
                    LF.addNodeInSortedOrder(parentNode,acquisitionNode);        // Adds new acquisition alfabetically sorted on the selected study.
                    //parentNode.add(acquisitionNode);   // Adds current acquisition at start of the corresponding study.
                }
            //}
        }
    }
    public void updateViewEditAcquisition(boolean isNew, String currentStudyDate, String study_Id, String oldAquisitionLaterality, String oldAquisitionTime, int acquisition_Id, String ImageLaterality, String AcquisitionTime) {
        System.out.println(">>> START OF updateViewEditAcquisition");  

        //String createdStudyName = null; // Catches the name of the new node.
        if (ImageLaterality != null && AcquisitionTime != null) {
            System.out.println("isNew: "+isNew);
            if(isNew){
                // Select current patient.
                TreePath path = updateViewSearch(frame.parseDate(currentStudyDate));
                
                if(path != null){   // Case of being a Patient, write the study inside its node.
                    DefaultMutableTreeNode changedNode = (DefaultMutableTreeNode)(MutableTreeNode) path.getLastPathComponent(); // Get the node of patient where we want to add an acquisition.
                    updateViewAddAcquisition(changedNode, acquisition_Id, ImageLaterality, AcquisitionTime, 1);  // Add a new Study node in a patient from JTree.
                }

            }else{  // Change the study node read from DB by a modifyed one.
                String oldEye = LF.eyeTranslation(oldAquisitionLaterality);
                TreePath path = updateViewSearch(oldEye+" "+oldAquisitionTime);
                System.out.println("oldAcquisition Laterality+Time: "+oldEye+" "+oldAquisitionTime+" Path: "+path);
                if(path != null){
                    String eye = LF.eyeTranslation(ImageLaterality);
                    DefaultMutableTreeNode changedNode = (DefaultMutableTreeNode)(MutableTreeNode) path.getLastPathComponent();    // Get's a node by it's path.

                    Acquisition z = (view.Acquisition)changedNode.getUserObject();
                    z.setLaterality(eye);
                    z.setTime(oldAquisitionTime);   // Although the acquisition is edited, maintains the acquisitionDate.
                    //createdAcquisitionName = z.toString();
                }
            }

            frame.modelPatient.reload();
            //updateViewSearch(createdAcquisitionName); // Selects the last created node.
        }else{
            System.out.println("The search textField is empty");
        }
    }

    public void updateViewDelete() {
        // Method 1
        TreePath path = null;
        // Find node to remove
        if(frame.PatientTree.getAnchorSelectionPath() != null){
            path = frame.PatientTree.getLeadSelectionPath();
        }
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) path.getLastPathComponent();
        //Patient p = (view.Patient)selectedNode.getUserObject();
        //System.out.println("Node deleted from PatientTree "+selectedNode.toString());

        frame.modelPatient.removeNodeFromParent(selectedNode);
        
    }
    public TreePath updateViewSearch(String Pattern) {
        TreePath path = null;
        int selectedTab = frame.jTabbedPane2.getSelectedIndex();    // Currently selected tab.
        int startRow = 0;

        if(frame.jTabbedPane2.getSelectedIndex() != 1){
            frame.jTabbedPane2.setSelectedIndex(1);
        }

        path = frame.PatientTree.getNextMatch(Pattern, startRow, Position.Bias.Forward);
        frame.PatientTree.setSelectionPath(path);
        frame.jTabbedPane2.setSelectedIndex(selectedTab);   // Returns to the preselected tab.
        return path;
    }
    /*public TreePath updateViewSearch(String Pattern) {
        TreePath path = null;
        
        if(frame.jTabbedPane2.getSelectedIndex() == 1){
            int startRow = 0;
            path = frame.PatientTree.getNextMatch(Pattern, startRow, Position.Bias.Forward);
            frame.PatientTree.setSelectionPath(path);
        }
        
        return path;
    }*/


}

